import axios from 'axios'
import { showToast } from 'vant'
// 跨域认证信息 header 名
const xsrfHeaderName = 'Authorization'

axios.defaults.timeout = 600000
axios.defaults.withCredentials = true
axios.defaults.xsrfHeaderName = xsrfHeaderName
axios.defaults.xsrfCookieName = xsrfHeaderName

// http method
const METHOD = {
  GET: 'get',
  POST: 'post',
  PUT: 'PUT',
  DELETE: 'delete'
}
/**
 * axios请求
 * @param url 请求地址
 * @param method {METHOD} http method
 * @param params 请求参数
 * @returns {Promise<AxiosResponse<T>>}
 */
async function request(url, method, params, config) {
  switch (method) {
    case METHOD.GET:
      return axios.get(url, { params, ...config })
    case METHOD.POST:
      console.log(params)
      return axios.post(url, params, config)
    case METHOD.PUT:
      return axios.put(url, params, config)
    case METHOD.DELETE:
      return axios.delete(url, { params, ...config })
    case METHOD.DELETEBODY:
      return axios.delete(url, { data: params, ...config })
    default:
      return axios.get(url, { params, ...config })
  }
}
import { showLoadingToast, closeToast } from 'vant'
// request拦截器
axios.interceptors.request.use(
  (config) => {
    // showLoadingToast({
    //   message: '加载中...',
    //   forbidClick: true,
    //   loadingType: 'spinner',
    //   iconSize: '150px',
    //   icon: 'https://img.zcool.cn/community/016ea057314efc0000002bf08c5256.gif',
    //   duration: 0
    // })
    // let userinfo = JSON.parse(localStorage.getItem('userinfo'))
    // config.headers['Authorization'] = userinfo.accessToken

    // config.headers['clientType'] = 'H5'
    // config.headers['H5cookie'] = 'code=' + userinfo.code + ';pcode=' + userinfo.pcode
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'

    return config
  },
  (error) => {
    Promise.reject(error)
  }
)
//配置响应拦截器
// 响应拦截器:在请求响应之后对数据处理，比如:登录失败、请求数据失败的处理
// instance.interceptors.response.use(response=>{l}, err=>{});
// 响应成功:执行回调函数1;响应失败，执行回调函数2
axios.interceptors.response.use(
  (response) => {
    let data = response.data
    closeToast()
    console.log(data)
    if (data.code == '500') {
      showToast(data.message)
    }
    return data //这里的response就是请求成功后的res , response.data即是请求成功后回调函数内的参数res.data
  },
  (err) => {
    closeToast()
    return Promise.reject(err) //将错误消息挂到promise的失败函数上
  }
)

export { METHOD, request }
